package cn.yangliu.nacos.comm.audit;

import java.util.Objects;
import java.util.Optional;

import cn.yangliu.nacos.comm.model.Oauth2UserModel;
import cn.yangliu.nacos.comm.tools.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-01
 */
@EnableJpaAuditing
public class JpaAuditor implements AuditorAware<String>, InitializingBean {

    /**
     * current class instance's member.
     * The Auditor handler.
     */
    @Autowired(required = false)
    private AuditorHandler auditorHandler;

    /**
     * current class method for getter.
     * Gets current auditor.
     *
     * @return the current auditor
     */
    @Override
    public Optional<String> getCurrentAuditor() {
        String operator = auditorHandler.handler();
        /**
         * anonymous
         */
        if (StringUtils.isBlank(operator)) {
            return Optional.of("anonymous");
        }
        return Optional.of(operator);
    }

    /**
     * After properties set.
     *
     * @throws Exception the exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        if (Objects.isNull(auditorHandler)) {
            auditorHandler = () ->{
                Oauth2UserModel userModel = SecurityUtils.getCurrentUser();
                if (Objects.isNull(userModel)){
                    return null;
                }
                return userModel.getUsername();
            };
        }
    }
}
